/**
 * import SocketMixin from 'mars-pro/lib/pro/socket/mixin'
 * 
 * Vue.use(SocketMixin, [
 *   //定义多个ws配置
 *   {
 *     wsUrl: '?',
 *     name: 'test',
 *     
 *   },
 *   {
 *     wsUrl: '?',
 *     name: 'test1',
 *   }
 * ])
 * 
 * //所有的组件中 都可以定义onReconnectingWebsocket 方法 用以接收ws消息
 * {
 *   methods:{
 *     onReconnectingWebsocket({type, data, message, name}){
 *       //处理业务逻辑
 *     }
 *  }
 * }
 * 
 * @author xiufu.wang
 * 
 */

import ReconnectingWebsocket from './reconnecting-websocket.js'

let wss = null;
let tasks = [];

function runTasks(...arg){
  for (let i = 0; i < tasks.length; i++) {
    const m = tasks[i]
    m(...arg)
  }
}

function createMultipleReconnectingWebsocket(vm, options) {
    options = options || [];
    options = Array.isArray(options) ? options : [options];
    if (options.length === 0) {
        return;
    }

    wss = options.map(function(r){
        const ws = new ReconnectingWebsocket(r);
        ws.run(null, runTasks)
        return ws;
    })

    //关闭
    return function(){
        for (let i = 0; i < wss.length; i++) {
            wss[i].close()
        }
        wss = null;
    }
}

export default {
    install(Vue, options) {
        Vue.mixin({
            methods: {
                //启动
                startProSocket() {
                    if (!wss) {
                        const opt = typeof options === 'function' ? options(this) : options
                        this._closeProSocket = createMultipleReconnectingWebsocket(this, opt);
                    }
                },
                //关闭
                closeProSocket() {
                    if (wss && this._closeProSocket) {
                        this._closeProSocket();
                    }
                }
            },
            mounted() {
                if (this.onReconnectingWebsocket) {
                    tasks.push(this.onReconnectingWebsocket)
                }
            },
            beforeDestroy() {
                if (this.onReconnectingWebsocket) {
                    tasks.splice(tasks.indexOf(this.onReconnectingWebsocket), 1)
                }
            }
        })
    }
}